/************************************************************************
* lighting.c
* voxelands - 3d voxel world sandbox game
* Copyright (C) Lisa 'darkrose' Milne 2016 <lisa@ltmnet.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program.  If not, see <http://www.gnu.org/licenses/>
************************************************************************/

#include "common.h"
#include "graphics.h"
#include "array.h"
#include "list.h"

static struct {
	int ids;
	array_t lights;
} light_data = {
	-1
};

/* comparison functions:
 * return 0 to insert
 * return 1 to insert later
 * return -1 to not insert at all
 */
static int light_insert_cmp(void *e1, void *e2)
{
	light_t *l1;
	light_t *l2;

	l1 = e1;
	l2 = e2;

	if (l1->d < l2->d)
		return 0;
	return 1;
}

int light_add(colour_t *colour, v3_t *pos, v3_t *att)
{
	light_t *l;
	if (light_data.ids < 0)
		array_init(&light_data.lights,ARRAY_TYPE_PTR);

	l = malloc(sizeof(light_t));
	if (!l)
		return -1;

	l->pos.x = pos->x;
	l->pos.y = pos->y;
	l->pos.z = pos->z;

	l->colour.r = colour->r;
	l->colour.g = colour->g;
	l->colour.b = colour->b;
	l->colour.a = colour->a;

	if (att) {
		l->att.x = att->x;
		l->att.y = att->y;
		l->att.z = att->z;
	}else{
		l->att.x = 1.0;
		l->att.y = 0.0;
		l->att.z = 0.0;
	}

	l->id = ++light_data.ids;

	array_push_ptr(&light_data.lights,l);

	return -1;
}

void light_remove(int id)
{
}

void light_bind_near(shader_t *s, v3_t *pos)
{
	int i;
	light_t *l;
	light_t *nearby = NULL;

	if (light_data.ids < 0)
		return;

	for (i=0; i<light_data.lights.length; i++) {
		l = array_get_ptr(&light_data.lights,i);
		if (!l)
			continue;
		l->d = math_distance(pos,&l->pos);
		nearby = list_insert_cmp(&nearby,l,light_insert_cmp);
	}

	l = nearby;
	for (i=0; l; i++) {
		shader_uniform_light(s,i,l);
		l = l->next;
	}
	for (; i<8; i++) {
		shader_uniform_light(s,i,NULL);
	}
}
